<template>
  <van-action-sheet v-bind="$attrs" round position="bottom" :closeable="false" :close-on-click-overlay="false">
    <van-form @submit="onSubmit">
      <van-field
        v-model.trim="followForm.followModeName"
        readonly
        required
        label="跟进方式"
        placeholder="请选择"
        :rules="followRules.followMode"
        @click="$set(show, 'mode', true)"
      ></van-field>
      <van-popup v-model="show.mode" round position="bottom">
        <van-picker
          title="请选择跟进方式"
          value-key="label"
          show-toolbar
          :columns="typeEnums"
          @cancel="show.mode = false"
          @confirm="modeChange"
        />
      </van-popup>

      <van-field
        v-model="followForm.recordContent"
        :rules="followRules.recordContent"
        type="textarea"
        rows="6"
        required
        autosize
        label="记录内容"
        placeholder="请输入"
      >
        <template #input>
          <div class="diy-input" @input="">
            <div
              class="contenteditable-textarea"
              v-html="followForm.recordContent"
              ref="contenteditable"
              contenteditable="true"
            >
              <!-- 初步
              <span contenteditable="false">@suer</span> -->
            </div>
            <van-button
              class="mt10"
              type="primary"
              size="mini"
              native-type="button"
              round
              @click="$set(show, 'user', true)"
            >
              添加协作成员
              <van-icon name="info" @click.native.stop="showDialog('user')" />
            </van-button>
          </div>
        </template>
      </van-field>

      <van-field
        readonly
        clickable
        name="datetimePicker"
        :value="followForm.cooperateTime"
        label="协作日期"
        placeholder="请选择"
        @click="
          $set(show, 'dateTime', true)
          followForm._cooperateTime = new Date(followForm.cooperateTime || new Date())
        "
      >
        <template #label>
          <span>协作日期</span>
          <van-icon name="info ml10" @click.native.stop="showDialog('datetime')" />
        </template>
      </van-field>
      <van-popup v-model="show.dateTime" position="bottom">
        <van-datetime-picker
          v-model="followForm._cooperateTime"
          title="选择日期和时间"
          type="datetime"
          @confirm="dateTimConfirm"
          @cancel="show.dateTime = false"
        />
      </van-popup>

      <van-field class=" upload" label="上传附件" placeholder="请选择">
        <template #label>
          <span>上传附件</span>
          <van-icon name="info ml10" @click.native.stop="showDialog('upload')" />
        </template>
        <template #input>
          <Upload
            ref="upload"
            :format="format"
            :fileList.sync="followForm.attachmentList"
            multiple
            limit="10"
            result-type="file"
          ></Upload>
        </template>
      </van-field>

      <div class="footer flex" style="margin: 20px;">
        <van-button class="" native-type="button" round block plain @click="cancel">取消</van-button>
        <van-button type="info" native-type="submit" round block class="ml10">提交</van-button>
      </div>
    </van-form>

    <!-- 选择人员 弹窗 -->
    <SelectStaff v-model="show.user" @change="selectStaff" />
  </van-action-sheet>
</template>

<script>
import { dateFormat } from '@/utils/index'

import { addFollow, getFollowMode } from './api'

import Upload from '@/components/Upload.vue'
import SelectStaff from './components/UserInfo.vue'

const form = {
  cooperateTime: dateFormat(new Date(), 'yyyy/MM/dd hh:mm'),
  _cooperateTime: new Date(),
  attachmentList: [
    // {attachmentAddress,attachmentName,attachmentType,followRecordId,id}
  ],
  followMode: null,
  recordContent: '请输入',
  cooperateUsers: [],
}
export default {
  components: { Upload, SelectStaff },
  props: {
    leadId: '',

    // add 添加跟进 replay 回复跟进 ,
    type: {
      type: String,
      default: 'add',
    },
  },
  data() {
    return {
      dateFormat,
      loading: false,

      fileList: [],

      clueStatusEnums: [],
      typeObj: {},
      typeEnums: [
        // { label: '电话联系', value: 0 },
        // { label: '企微沟通', value: 1 },
        // { label: '短信跟进', value: 2 },
        // { label: '现场沟通', value: 3 },
        // { label: '其他跟进', value: 4 }
      ],
      consultEnum: [],
      isOpen: false,
      loading: false,
      followForm: JSON.parse(JSON.stringify(form)),
      followRules: {
        followMode: [{ required: true, message: '', trigger: 'blur' }],
        recordContent: [{ required: true, message: '', trigger: 'blur' }],
        consult: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        pendingStatusCode: [{ required: true, message: '请选择线索状态', trigger: 'blur' }],
      },
      pendingStatusCode: null,
      minDate: new Date(),
      showAppointmentTime: false,
      showMode: false,
      showTip: false,
      showDateTime: false,
      showConsult: false,
      showWxstatus: false,
      showNearbyArea: false,
      showLeadsStatus: false,
      consult: [],
      leadsStatus: [],
      weixinStatusEnum: {
        0: '验证中',
        1: '不存在',
        2: '加微信已通过',
      },
      wxStatus: [
        { label: '验证中', value: 0 },
        { label: '不存在', value: 1 },
        { label: '加微信已通过', value: 2 },
      ],
      nearbyArea: [],
      nearbyAreaOld: [],
      allNearbyArea: [],
      searchName: '',
      primaryArea: '',
      secondAreaList: [],
      secondArea: '',
      thirdAreaList: [],
      thirdArea: '',
      leadsId: null,
      format: ['png', 'jpg', 'jpeg', 'mp4', 'mov', 'doc', 'docx', 'pdf', 'ppt', 'pptx', 'pps', 'pptsx', 'xls', 'xlsx'],
      maxSizeDefault: { 0: 20, 1: 2, 2: 100, 3: 50 },
      // 图片的宽高像素限制 [width(number), height(number)],默认null不限制
      maxImgPx: [1440, 1080],

      show: {},
    }
  },
  watch: {},
  computed: {},
  created() {
    // this.leadsId = this.$route.query.id
  },
  mounted() {
    this.getFollowMode()
  },
  methods: {
    // 获取跟进方式
    getFollowMode() {
      getFollowMode().then((res) => {
        const data = res.data,
          typeEnums = []
        for (const key in data) {
          if (Object.hasOwnProperty.call(data, key)) {
            const element = { label: key, value: data[key] }
            typeEnums.push(element)
          }
        }
        this.typeEnums = typeEnums
      })
    },

    // 选择跟进方式
    modeChange(v) {
      this.followForm.followMode = v.value
      this.followForm.followModeName = v.label
      this.show.mode = false
    },
    contentedit(v) {
      // debugger
      this.followForm.recordContent = this.$refs.contenteditable.innerHTML
    },
    selectStaff(list) {
      // debugger
      // this.followForm._cooperateUsers = list.map((e) => e.userName).join(',')
      let selObj = window.getSelection()
      let anchorNode = selObj.anchorNode

      let atUser = ''
      list.forEach((e) => {
        atUser += `&nbsp;<span contenteditable="false" class="at-user ${e.weUserId}">@${e.userName}</span>&nbsp;`
      })

      if (anchorNode && anchorNode.textContent) {
        let innerHTML =
          anchorNode.textContent.slice(0, selObj.anchorOffset) +
          atUser +
          anchorNode.textContent.slice(selObj.anchorOffset)

        if (anchorNode.nodeType == 3) {
          if (anchorNode.parentElement.innerHTML === anchorNode.textContent) {
            anchorNode.parentElement.innerHTML = innerHTML
          } else {
            let sp = document.createElement('span')
            sp.innerHTML = innerHTML
            anchorNode.replaceWith(sp)
            // anchorNode.parentElement.replaceChild(anchorNode)
          }
        }
      } else {
        this.$toast('请先选中 记录内容 输入框')
      }

      // this.$refs.contenteditable.innerHTML = this.followForm.recordContent
      list.forEach((element) => {
        this.followForm.cooperateUsers.some((e) => e.weUserId == element.weUserId) ||
          this.followForm.cooperateUsers.push(element)
      })
    },
    dateTimConfirm(val) {
      this.followForm.cooperateTime = dateFormat(val, 'yyyy/MM/dd hh:mm')
      this.show.dateTime = false
    },

    showDialog(type) {
      let dict = {
        user: {
          title: '添加协作',
          message: '添加协作成员可通知其他同事帮助自己跟进当前线索，例如请求对方提供相关资料、协同参会等。',
        },
        datetime: {
          title: '协作日期',
          message:
            '协作日期可指定某一天与该线索客户的约定事项进行跟进，例如本次跟进约定本周三进行见面约谈或者线上会议。\n如果添加了协作成员也会提醒协作成员协助参与',
        },
        upload: {
          title: '附件要求',
          message:
            '仅支持上传视频、图片与文件，共不超过10个。\n①视频仅支持mp4、mov；单个限制100M\n②图片仅支持jpg、png、jpeg；单个限制20M\n③文件仅支持pdf、ppt、word；单个限制50M',
        },
      }
      this.$dialog.alert({
        title: dict[type].title,
        message: dict[type].message,
        confirmButtonText: '我知道了',
        messageAlign: 'left',
        theme: 'round-button',
      })
    },
    cancel() {
      this.$emit('input', false)
      // this.$router.replace({ name: 'highSeasDetail', query: this.$route.query })
    },
    onSubmit() {
      const toast = this.$toast.loading()

      this.followForm.recordContent = this.$refs.contenteditable.innerHTML
      const params = JSON.parse(JSON.stringify(this.followForm))

      let atUserEls = this.$refs.contenteditable.getElementsByClassName('at-user')
      // debugger
      let atUserWeUserIds = Array.from(atUserEls).map((element) => element.classList[1])
      params.cooperateUsers = params.cooperateUsers.filter((e) => atUserWeUserIds.includes(e.weUserId))

      params.weLeadsId = this.leadId
      params.attachmentList = params.attachmentList.map((e) => ({
        attachmentType: e.myType,
        attachmentName: e.name,
        attachmentAddress: e.url,
      }))
      // if (params.appointmentTime) params.appointmentTime = dateFormat(params.appointmentTime, 'yyyy-MM-dd hh:mm:ss')

      // 提交信息
      addFollow(params)
        .then((res) => {
          this.loading = false
          this.$toast.success('操作成功')
          this.$emit('success')
          this.cancel()
          this.followForm = JSON.parse(JSON.stringify(form))
        })
        .finally(() => {
          toast.clear()
        })
    },
  },
}
</script>

<style lang="less" scoped>
.van-action-sheet__content {
  overflow-y: visible;
}
.diy-input {
  width: 100%;
  .contenteditable-textarea {
    width: 100%;
    min-height: 100px;
    text-align: left;
  }
  ::v-deep .at-user {
    color: @color;
    padding: 0 3px;
  }
}
</style>
